import React, { Component } from 'react'
import { observer, inject } from 'mobx-react'
import PropTypes from 'prop-types'
import Helmet from 'react-helmet'
import queryString from 'query-string'
import List from '@material-ui/core/List'
import { Tabs, Tab, CircularProgress } from '@material-ui/core'

import Container from '../layout/container'
import TopicListItem from './list-item'

import { tabs } from '../../utils/variable-default'

@inject(stores => (
  {
    appState: stores.appState,
    topicStore: stores.topicStore,
  }
)) @observer

class TopicList extends Component {
  constructor(props) {
    super(props)
    this.changeTabIndex = this.changeTabIndex.bind(this)
  }

  componentDidMount() {
    const tab = this.getTab()
    const { topicStore } = this.props
    topicStore.fetchTopics(tab)
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.location.search !== this.props.location.search) {
      this.props.topicStore.fetchTopics(this.getTab(nextProps.location.search))
    }
  }

  getTab(search) {
    const { location } = this.props
    search = search || location.search
    const query = queryString.parse(search)
    return query.tab || 'share'
  }

  bootstrap() {
    const { appState } = this.props
    return new Promise((resolve) => {
      appState.count = 99
      resolve(true)
    })
  }

  changeTabIndex(event, value) {
    this.props.history.push({
      pathname: '/list',
      search: `?tab=${value}`,
    })
  }

  listItemClick(topic) {
    this.props.history.push(`/detail/${topic.id}`)
  }

  render() {
    const { topicStore } = this.props

    const topicList = topicStore.topics
    const syncingTopic = topicStore.syncing
    const tab = this.getTab()

    return (
      <Container>
        <Helmet>
          <title>This is topic list</title>
          <meta name="description" content="This is description" />
        </Helmet>
        <Tabs value={tab} onChange={this.changeTabIndex}>
          {
            Object.keys(tabs).map(item => (
              <Tab label={tabs[item]} value={item} key={item} />
            ))
          }
        </Tabs>
        <List>
          {
            topicList.map(topic => <TopicListItem key={topic.id} handleClick={() => this.listItemClick(topic)} topic={topic} />)
          }
          {
            syncingTopic ? (
              <div
                style={{
                  display: 'flex',
                  justifyContent: 'space-around',
                  padding: '120px 0 100px',
                }}
              >
                <CircularProgress color="primary" size={100} />
              </div>
            ) : null
          }
        </List>
      </Container>
    )
  }
}

TopicList.wrappedComponent.propTypes = {
  appState: PropTypes.object.isRequired,
  topicStore: PropTypes.object.isRequired,
}

TopicList.propTypes = {
  location: PropTypes.object.isRequired,
  history: PropTypes.object.isRequired,
}

export default TopicList
